<?php
namespace App\Services\System;

use App\Models\ActivityInfo;
use App\Models\ActivityInfoPartNames;
use App\Models\DictionaryItem;
use App\Models\File;
use App\Models\Files;
use App\Models\FormInstance;
use App\Models\Participant;
use App\Models\StudyStage;
use App\Models\System\Menu;
use App\Models\System\Tasks;
use App\Models\System\Term;
use App\Models\SystemTask;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class ActivityService
{
    /** @var \App\Repositories\System\ActivityRepository $activityRepository */
    private $activityRepository;
    /** @var \App\Repositories\System\ParticipantRepository $participantRepository */
    private $participantRepository;
    /** @var \App\Repositories\System\SystemTaskRepository $systemTaskRepository */
    private $systemTaskRepository;

    private $partNamesArr = [
        'TEACHERTRAINING_OUTTRAINING_TABLE',
        'TEACHERTRAINING_OTHER_TABLE',
    ];

    public function __construct()
    {
        $this->activityRepository = app('activityRepository');
        $this->participantRepository = app('participantRepository');
        $this->systemTaskRepository = app('systemTaskRepository');
    }

    /**
     * @Description: 获取活动列表信息数据
     * @Author: kzj
     * @datetime: 2022-11-21
     */
    public function getList($request)
    {
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;
        $formKey = NULL;
        $termId = 0;
        $name = '';
        $status = '';
        $hostName = ''; //主持人
        $beginDate = '';
        $endDate = '';
        $joinName = '';
        $creatorName = '';
        $zm_gkk_category = '';
        $jyzCode = '';
        $rangeDate = [];
        $jsonSearch = [];

        $user = Auth::user();
        //dd($user);
        $roleType = $user->cur_role_type;
        $currRoleId = $user->curr_role_id;
        //var_dump($currRoleId);
        // dd($roleType);

        if (isset($request['search']['activity_category'] )&& !empty($request['search']['activity_category'])){
            $formKey = $request['search']['activity_category'];
        } else {
            // 公开教学 // 经验交流 // 论文发表 // 论著发表
            if (isset($request['form_key'] )&& !empty($request['form_key'])){
                if($request['form_key'] == 'TEARRESEARCH_EXCHANGE_TABLE') {//经验交流
                    if($roleType == 1) {
                        $formKey = 'EW_EXCHANGE_EXPERIENCE_TABLE';
                    } else if ($roleType == 2) {
                        $formKey = 'TEARRESEARCH_EXCHANGE_TABLE';
                    } else {
                        $formKey = [$request['form_key'], 'EW_EXCHANGE_EXPERIENCE_TABLE'];
                    }
                } else if($request['form_key'] == 'TEARRESEARCH_OPEN_TABLE') {//公开教学
                    // 教育工作 - 班队会：合并到公开教学；原班队会的数据移至公开教学模块中，类型为教育；原公开教学的数据，类型为教学
                    if($roleType == 1) {
                        $formKey = 'EW_CLASS_MEETING_TABLE';//班队会
                    } else if ($roleType == 2) {
                        $formKey = 'TEARRESEARCH_OPEN_TABLE';
                    } else {
                        $formKey = [$request['form_key'], 'EW_CLASS_MEETING_TABLE'];
                    }
                // } else if($request['form_key'] == 'TEARRESEARCH_SUBJECT_STUDY_TABLE') {//课题研究
                //     $formKey = [$request['form_key'], 'EW_SUBJECT_RESEARCH_TABLE'];
                } else if($request['form_key'] == 'TEARRESEARCH_PUBLISH_TABLE') {//论文论著发表
                    if($roleType == 1) {
                        $formKey = 'EW_PAPER_PUBLISH_TABLE';
                    } else if ($roleType == 2) {
                        $formKey = 'TEARRESEARCH_PUBLISH_TABLE';
                    } else {
                        $formKey = [$request['form_key'], 'EW_PAPER_PUBLISH_TABLE'];
                    }
                } else {
                    $formKey = $request['form_key'] ?? '';
                }
            }
        }
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $name = $request['search']['name'];
        }
        if (isset($request['search']['status']) && !empty($request['search']['status'])){
            $status = $request['search']['status'];
        }
        if (isset($request['search']['host_name']) && !empty($request['search']['host_name'])){
            $hostName = $request['search']['host_name'];
        }
        if (isset($request['search']['jyz_code']) && !empty($request['search']['jyz_code'])){
            $jyzCode = $request['search']['jyz_code'];
        }
        if (isset($request['search']['begin_date']) && !empty($request['search']['begin_date'])){
            $beginDate = $request['search']['begin_date'];
        }
        if (isset($request['search']['end_date']) && !empty($request['search']['end_date'])){
            $endDate = $request['search']['end_date'];
        }
        if (isset($request['search']['zm_gkk_category'] )&& !empty($request['search']['zm_gkk_category'])){
            $zm_gkk_category = $request['search']['zm_gkk_category'];
        }
        //通过json的类型及optionId值进行查询
        if (isset($request['json_search']['pubications_publish_type'] )&& !empty($request['json_search']['pubications_publish_type'])){
            $jsonSearch['pubications_publish_type'] = $request['json_search']['pubications_publish_type'];
        }
        if (isset($request['search']['level'] )&& !empty($request['search']['level'])){
            $jsonSearch['level'] = $request['search']['level'];
        }
        if (isset($request['search']['course'] )&& !empty($request['search']['course'])){
            $jsonSearch['course'] = $request['search']['course'];
        }
        if (isset($request['search']['grade'] )&& !empty($request['search']['grade'])){
            $jsonSearch['grade'] = $request['search']['grade'];
        }
        $grades = '';
        if (isset($request['search']['grades'] )&& !empty($request['search']['grades'])){
            $grades = $request['search']['grades'];
        }
        if (isset($request['search']['class_item'] )&& !empty($request['search']['class_item'])){
            $jsonSearch['class_item'] = $request['search']['class_item'];
        }
        // if (isset($request['search']['witness'] )&& !empty($request['search']['witness'])){
        //     $jsonSearch['witness'] = $request['search']['witness'];
        // }
        // if (isset($request['search']['awarding_unit'] )&& !empty($request['search']['awarding_unit'])){
        //     $jsonSearch['awarding_unit'] = $request['search']['awarding_unit'];
        // }
        // if (isset($request['search']['guided_teacher'] )&& !empty($request['search']['guided_teacher'])){
        //     $jsonSearch['guided_teacher'] = $request['search']['guided_teacher'];
        // }
        // if (isset($request['search']['guided_teacher_school'] )&& !empty($request['search']['guided_teacher_school'])){
        //     $jsonSearch['guided_teacher_school'] = $request['search']['guided_teacher_school'];
        // }
        // if (isset($request['search']['proof_material'] )&& !empty($request['search']['proof_material'])){
        //     $jsonSearch['proof_material'] = $request['search']['proof_material'];
        // }
        if (isset($request['search']['category'] )&& !empty($request['search']['category'])){
            $jsonSearch['category'] = $request['search']['category'];
        }
        if (isset($request['search']['reception_class'] )&& !empty($request['search']['reception_class'])){
            $jsonSearch['reception_class'] = $request['search']['reception_class'];
        }
        if (isset($request['search']['date_range'] )&& !empty($request['search']['date_range'])){
            $rangeDate = explode(' - ', $request['search']['date_range']);
        }
        if (isset($request['search']['join_name'] )&& !empty($request['search']['join_name'])){
            $joinName = $request['search']['join_name'];
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $creatorName = $request['search']['creator_name'];
        }
        $user = Auth::user();
        $viewAll = $this->activityRepository->getViewPower($request['form_key']);
        // dd($formKey, $jsonSearch, $status, $viewAll);
        //DB::connection()->enableQueryLog();

        $result = ActivityInfo::select('activity_info.*', 'b.status')
            ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
            ->leftJoin('participant as p', 'activity_info.id', '=', 'p.activity_info_id')

            ->when($formKey, function($q) use($formKey) {
                if(is_array($formKey)) {
                    $q->whereIn('activity_info.activity_category', $formKey);
                } else {
                    $q->where('activity_info.activity_category', $formKey);
                }
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($query) use($request,$user){//处理档案袋只查看自己创建或者主持人参与教师的数据
                $query->whereRaw("((`activity_info`.`creator_id` = ".$request['user_id'].") or (`p`.`user_id` = ".$request['user_id']." and `b`.`status` != 'FILL_IN')) ");
            })
            ->when(!isset($request['user_id']), function($q) use($name) {
                $q->manageable();
            })
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('activity_info.data_version_id', $termId);
                });
            })
            ->when($name, function($q) use($name) {
                $q->where('activity_info.name', 'like', '%' . $name . '%');
            })
            ->when($status, function($q) use($status) {
                $q->where('b.status', '=', $status);
            })
            ->when($zm_gkk_category, function($q) use($zm_gkk_category) {
                $q->where('activity_info.zm_gkk_category', '=', $zm_gkk_category);
            })
            ->when($beginDate, function($q) use($beginDate) {
                $q->where('activity_info.begin_date', '=', $beginDate);
            })
            ->when($jyzCode, function($q) use($jyzCode) {
                $q->where('activity_info.jyz_code', '=', $jyzCode);
            })
            ->when($endDate, function($q) use($endDate) {
                $q->where('activity_info.end_date', '=', $endDate);
            })
            ->when(!empty($jsonSearch), function($q) use($jsonSearch) {
                foreach($jsonSearch as $k => $id) {
                    $q->whereRaw(" JSON_EXTRACT(activity_info.`".$k."`,'$[0].optionId') = $id");
                }
            })
            ->when(!empty($grades), function($q) use($grades) {
                $q->whereRaw(" find_in_set($grades,activity_info.grade_ids_data) ");
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('activity_info.begin_date', '<=', $rangeDate[0])->where('activity_info.end_date', '>=', $rangeDate[1]);
            })
            ->when($hostName, function($q) use($hostName, $formKey) {
                $bool = in_array($formKey, $this->partNamesArr);
                $q->whereHas($bool ? 'partNames' :'compereUser', function ($query) use($hostName, $bool) {
                    $query->where($bool? 'host_name' :'nickname', 'like', '%' . $hostName . '%');
                });
            })
//            ->when(!isset($request['user_id']), function($q) use($user, $viewAll){//处理非档案袋只查看自己的数据
//                if($user->curr_role_id != 11) {//学校管理员
//                    $q->when(!$viewAll && !$user->is_checker, function ($qq) use ($user) {
//                        $qq->where('activity_info.creator_id', $user->id)->where(function ($query) use ($user) {
//                            $query->whereHas('participants', function ($qqy) use ($user) {
//                                $qqy->where('user_id', $user->id);
//                            })->orDoesntHave('participants');
//                        });
//                    });
//                }
//            })
            ->when($joinName, function($q) use($joinName) {
                $q->whereHas('joinUser', function ($query) use($joinName) {
                    $query->where('nickname', 'like', '%' . $joinName . '%');
                });
            })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('creator', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->when(!empty($request['search']['materials_date']),function($q) use($request){
                return $q->whereRaw(" activity_info.data_version_id in ({$request['search']['materials_date']})");
            })
            ->when(!empty($request['search']['whereStr']),function($q) use($request){
                return $q->whereRaw($request['search']['whereStr']);
            })
            ->with('term', 'forminstance', 'compere', 'participant', 'creator', 'partNames', 'instance:id,status')
            ->where('activity_info.deleted', 0)
            ->orderBy('activity_info.id', 'desc')
            ->groupBy('activity_info.id')
            ->paginate($limit, '*', 'page', $page)
            ->toArray();
        if(!empty($request['form_key']) && $request['form_key'] == 'TEACHING_REFLECT_TABLE'){
            $dictResponse = DB::table('dicitems')->where('diccode','JYZ')->get()->toArray();
            $dictArray = array_column($dictResponse,'itemname','itemcode');
        }
        foreach ($result['data'] as &$item){
            if(!empty($request['form_key']) && $request['form_key'] == 'TEACHING_REFLECT_TABLE'){
                $item['jyz_name'] = $dictArray[$item['jyz_code']] ?? '';
            }
            if($user->id == $item['creator_id']) {
                $item['is_createor'] = 1;
            }else{
                $item['is_createor'] = 0;
            }
            $item['is_part'] = 0;
            if(!empty($item['participant'])) {
                $participant = array_column($item['participant'], 'user_id');
                if (in_array($user->id, $participant) && $item['is_createor'] != 1) {
                    $item['is_part'] = 1;
                }
            }
            /**
            $jyzName = '';
            if ($item['jyz_code']){
                $jyzName = DB::table('dicitems')->find($item['jyz_code'])->itemname;
            }
            $item['jyz_name'] = $jyzName;**/
        }
//        dd(DB::getQueryLog());
        return $result;
    }

    //经验交流
    public function getJyjlList($request)
    {
        $materials_array = explode(',',$request['materials_date']) ;
        $user_id = $request['user_id'];
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;
        $result =  ActivityInfo::select('activity_info.*', 'b.status')
                    ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                    ->whereIn('activity_info.activity_category',['TEARRESEARCH_EXCHANGE_TABLE','EW_EXCHANGE_EXPERIENCE_TABLE'])
                    ->where('b.status','PASS')
                    ->whereIn('activity_info.data_version_id',$materials_array)
                    ->where('activity_info.deleted', 0)
                    // ->when($user_id, function($q) use($user_id){
                    //     $q->whereHas('participants', function($query) use($user_id){
                    //         $query->where('user_id', $user_id);
                    //     });
                    // })
                    ->where('activity_info.creator_id',$user_id)
                    ->with('term', 'forminstance', 'compere', 'participant', 'creator', 'instance:id,status')
                    ->orderBy('activity_info.id', 'desc')
                    ->paginate($limit, '*', 'page', $page)
                    ->toArray();
        return $result;
    }

    //课题研究
    public function getKtyjList($request)
    {
        $materials_array = explode(',',$request['materials_date']) ;
        $user_id = $request['user_id'];
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;
        $result =  ActivityInfo::select('activity_info.*', 'ss.status', 'b.status as old_status')
                    ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                    ->leftJoin('participant as d','activity_info.id','=','d.activity_info_id')
                    ->leftJoin('study_stage as ss', function ($join) {
                        //$join->on('activity_info.id', '=', 'ss.activity_id')->on('activity_info.stage', '=', 'ss.stage');
                        $join->on('activity_info.id', '=', 'ss.activity_id');
                    })
                    ->whereIn('activity_info.activity_category',['TEARRESEARCH_SUBJECT_STUDY_TABLE','EW_SUBJECT_RESEARCH_TABLE'])
                    ->whereIn('activity_info.data_version_id',$materials_array)
                    ->whereRaw(" ( (ss.stage =4 and ss.status = 2 ) or  b.status = 'PASS') ")
                    ->where('activity_info.deleted', 0)
                    // ->when($user_id, function($q) use($user_id){
                    //     $q->whereHas('participants', function($query) use($user_id){
                    //         $query->where('user_id', $user_id);
                    //     });
                    // })
                    //->whereRaw("(activity_info.creator_id = {$user_id} or d.user_id={$user_id})")
                    ->whereRaw("(d.user_id={$user_id})")
                    ->with('term', 'forminstance', 'compere', 'participant', 'creator', 'stages', 'instance:id,status')
                    ->orderBy('activity_info.id', 'desc')
                    ->groupBy('activity_info.id')
                    ->paginate($limit, '*', 'page', $page)
                    ->toArray();
        return $result;
    }

    //论文发表
    public function getLwfbList($request)
    {
        $materials_array = explode(',',$request['materials_date']) ;
        $user_id = $request['user_id'];
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;
        $result =  ActivityInfo::select('activity_info.*', 'b.status')
                    ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                    ->leftJoin('participant as d','activity_info.id','=','d.activity_info_id')
                    ->whereIn('activity_info.activity_category',['EW_PAPER_PUBLISH_TABLE','TEARRESEARCH_PUBLISH_TABLE'])
                    ->where('b.status','PASS')
                    ->whereIn('activity_info.data_version_id',$materials_array)
                    ->whereRaw(" JSON_EXTRACT(`activity_info.`pubications_publish_type`,'$[0].optionId') = 128")
                    ->where('activity_info.deleted', 0)
                    // ->when($user_id, function($q) use($user_id){
                    //     $q->whereHas('participants', function($query) use($user_id){
                    //         $query->where('user_id', $user_id);
                    //     });
                    // })
                    //->whereRaw("(activity_info.creator_id = {$user_id} or d.user_id={$user_id})")
                    ->whereRaw("(d.user_id={$user_id})")
                    ->with('term', 'forminstance', 'compere', 'participant', 'creator', 'instance:id,status')
                    ->orderBy('activity_info.id', 'desc')
                    ->groupBy('activity_info.id')
                    ->paginate($limit, '*', 'page', $page)
                    ->toArray();
        return $result;
    }

    //论著发表
    public function getLzfbList($request)
    {
        $materials_array = explode(',',$request['materials_date']) ;
        $user_id = $request['user_id'];
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;
        $result =  ActivityInfo::select('activity_info.*', 'b.status')
                    ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                    ->leftJoin('participant as d','activity_info.id','=','d.activity_info_id')
                    ->whereIn('activity_info.activity_category',['EW_PAPER_PUBLISH_TABLE','TEARRESEARCH_PUBLISH_TABLE'])
                    ->where('b.status','PASS')
                    ->whereIn('activity_info.data_version_id',$materials_array)
                    ->whereRaw(" JSON_EXTRACT(activity_info.`pubications_publish_type`,'$[0].optionId') = 129")
                    ->where('activity_info.deleted', 0)
                    // ->when($user_id, function($q) use($user_id){
                    //     $q->whereHas('participants', function($query) use($user_id){
                    //         $query->where('user_id', $user_id);
                    //     });
                    // })
                    //->whereRaw("(activity_info.creator_id = {$user_id} or d.user_id={$user_id})")
                    ->whereRaw("(d.user_id={$user_id})")
                    ->with('term', 'forminstance', 'compere', 'participant', 'creator', 'instance:id,status')
                    ->orderBy('activity_info.id', 'desc')
                    ->groupBy('activity_info.id')
                    ->paginate($limit, '*', 'page', $page)
                    ->toArray();
        return $result;
    }

    /**
     * @Description: 课题研究列表查询
     * @Author: kzj
     * @datetime: 2023-05-04
     */
    public function getStudyList($request)
    {
        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;
        // dd($request);
        $termId = 0;
        $name = '';
        $stage = 0;
        $status = -1;
        $oldStatus = "";
        $hostName = ''; //主持人
        $creatorName = ''; //创建人
        $rangeDate = [];
        $jsonSearch = [];

        $user = Auth::user();

        $roleType = $user->cur_role_type;
        if($roleType == 1) {
            $formKey = 'EW_SUBJECT_RESEARCH_TABLE';
        } else if ($roleType == 2) {
            $formKey = 'TEARRESEARCH_SUBJECT_STUDY_TABLE';
        } else {
            if (isset($request['search']['activity_category'] )&& !empty($request['search']['activity_category'])){
                $formKey = $request['search']['activity_category'];
            } else {
                $formKey = ['EW_SUBJECT_RESEARCH_TABLE', 'TEARRESEARCH_SUBJECT_STUDY_TABLE'];
            }
        }
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $name = $request['search']['name'];
        }
        $status = isset($request['search']['status'])?$request['search']['status']:-1;
        if (isset($request['search']['status'])){
            switch($status) {
                case '0':
                    $oldStatus = 'FILL_IN';
                    break;
                case '1':
                    $oldStatus = 'REVIEW';
                    break;
                case '2':
                    $oldStatus = 'PASS';
                    break;
                case '3':
                    $oldStatus = 'REVIEW_FAIL';
                    break;
            }
        }
        // dd($status, $oldStatus);
        if (isset($request['search']['host_name']) && !empty($request['search']['host_name'])){
            $hostName = $request['search']['host_name'];
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $creatorName = $request['search']['creator_name'];
        }
        if (isset($request['search']['stage'] )&& !empty($request['search']['stage'])){
            $stage = $request['search']['stage'];
        }
        //通过json的类型及optionId值进行查询
        if (isset($request['search']['pubications_publish_type'] )&& !empty($request['search']['pubications_publish_type'])){
            $jsonSearch['pubications_publish_type'] = $request['search']['pubications_publish_type'];
        }
        if (isset($request['search']['level'] )&& !empty($request['search']['level'])){
            $jsonSearch['level'] = $request['search']['level'];
        }
        if (isset($request['search']['category'] )&& !empty($request['search']['category'])){
            $jsonSearch['category'] = $request['search']['category'];
        }
        if (isset($request['search']['date_range'] )&& !empty($request['search']['date_range'])){
            $rangeDate = explode(' - ', $request['search']['date_range']);
        }
        // $user = Auth::user();
        $viewAll = $this->activityRepository->getViewPower($request['form_key']);
        // $result = ActivityInfo::select('activity_info.*', 'ss.status')
        //DB::connection()->enableQueryLog();
        $result = ActivityInfo::select('activity_info.*', 'ss.status', 'b.status as old_status')
            ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
            ->leftJoin('study_stage as ss', function ($join) {
                $join->on('activity_info.id', '=', 'ss.activity_id')->on('activity_info.stage', '=', 'ss.stage');
            })
            ->leftJoin('participant as p', 'activity_info.id', '=', 'p.activity_info_id')
            ->when(!isset($request['user_id']), function($q) use($name) {
                $q->manageable();
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($query) use($request,$user){//处理档案袋只查看自己创建或者主持人参与教师的数据
                $query->whereRaw("((`activity_info`.`creator_id` = ".$request['user_id'].") or (`p`.`user_id` = ".$request['user_id']." and `b`.`status` != 'FILL_IN'))");
            })
            // ->whereIn('activity_info.activity_category', ['TEARRESEARCH_SUBJECT_STUDY_TABLE', 'EW_SUBJECT_RESEARCH_TABLE'])
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('activity_info.data_version_id', $termId);
                });
            })
            ->when($formKey, function($q) use($formKey) {
                if(is_array($formKey)) {
                    $q->whereIn('activity_info.activity_category', $formKey);
                } else {
                    $q->where('activity_info.activity_category', $formKey);
                }
            })
            ->when($name, function($q) use($name) {
                $q->where('activity_info.name', 'like', '%' . $name . '%');
            })
            ->when($status >= 0, function($q) use($status, $oldStatus) {
                 $q->where('ss.status', '=', $status);
                /**$q->where(function($query) use($status, $oldStatus) {
                    $query->where('ss.status', '=', $status)->orWhere('b.status', '=', $oldStatus);
                });**/
            })
            ->when($stage > 0, function($query) use($stage) {
                $query->where('activity_info.stage', '=', $stage);
            })
            ->when(!empty($jsonSearch), function($q) use($jsonSearch) {
                foreach($jsonSearch as $k => $id) {
                    $q->whereRaw(" JSON_EXTRACT(activity_info.`".$k."`,'$[0].optionId') = $id");
                }
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('activity_info.begin_date', '<=', $rangeDate[0])->where('activity_info.end_date', '>=', $rangeDate[1]);
            })
            ->when($hostName, function($q) use($hostName) {
                $q->whereHas('compereUser', function ($query) use($hostName) {
                    $query->where('nickname', 'like', '%' . $hostName . '%');
                });
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($q) use($request){//处理档案袋只查看自己的数据
                $q->manageable();
                // $q->where('activity_info.creator_id', $request['user_id']);//
            })
            ->when(!isset($request['user_id']) && !$viewAll && !$user->is_checker, function($q) use($user){//处理非档案袋只查看自己的数据
                $q->whereHas('participants', function($query) use($user){
                    $query->where('user_id', $user->id);
                });
            })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('creator', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->when(!empty($request['search']['materials_date']),function($q) use($request){
                return $q->whereRaw(" activity_info.data_version_id in ({$request['search']['materials_date']})");
            })
            ->when(!empty($request['search']['whereStr']),function($q) use($request){
                return $q->whereRaw($request['search']['whereStr']);
            })
            ->with('term', 'forminstance', 'compere', 'participant', 'creator', 'stages', 'instance:id,status')
            ->where('activity_info.deleted', 0)
            ->orderBy('activity_info.id', 'desc')
            ->groupBy('activity_info.id')
            ->paginate($limit, '*', 'page', $page)
            ->toArray();
           // dd(DB::getQueryLog());
        foreach ($result['data'] as &$item){
            if($user->id == $item['creator_id']) {
                $item['is_createor'] = 1;
            }else{
                $item['is_createor'] = 0;
            }
            $item['is_part'] = 0;
            if($item['participant']) {
                $participant = array_column($item['participant'], 'user_id');
                if (in_array($user->id, $participant) && $item['is_createor'] != 1) {
                    $item['is_part'] = 1;
                }
            }
        }
        return $result;
    }


    /**
     * @Description: 活动添加
     * @Author: kzj
     * @datetime: 2023-02-28
     */
    public function add($request)
    {
        if(empty($request['activity_category'])) {
            throw new \Exception('参数缺失！');
        }

        if(in_array($request['activity_category'], ['TEARRESEARCH_EXCHANGE_TABLE', 'EW_EXCHANGE_EXPERIENCE_TABLE']) && !$request['files']['zmd'] && !$request['status'] == 1) {
            throw new \Exception('请上传证明单！');
        }
        /**
        if($request['activity_category'] == 'TEACHING_REFLECT_TABLE' && $request['status'] != 2) {//教学反思（案例）一学期只能加一个数据
            $activityResponse = ActivityInfo::leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
            ->where('status','!=','FILL_IN')
            ->where('activity_info.data_version_id',$request['data_version_id'])
            ->where('activity_info.deleted',0)
            ->where('activity_info.activity_category',$request['activity_category'])
            ->first();

            if($activityResponse) {
                throw new \Exception('一学期只能添加一个');
            }
        }**/
        // dd($request);
        $user = Auth::user();
        $term = Term::where('id', $request['data_version_id'])->first();
        $status = $request['status'] == 1 ? 'REVIEW' : 'FILL_IN';
        $oldStatus = $request['status'];
        $doTask = isset($request['do_task']) ? $request['do_task'] : 0;
        unset($request['file']);
        unset($request['status']);

        try{
            DB::beginTransaction();
            $gradeIds = $request['grade'] ?? '';
            //请求数据处理
            $activityData = $this->activityRepository->dealRequestData($request);
            //添加状态及审核信息
            $formInstance = FormInstance::create([
                'data_version_id' => $request['data_version_id'],
                'data_version_name' => $term->title,
                'form_key' => $request['activity_category'],
                'type' => 'MainForm',
                'owner_id' => $user->id,
                'status' => $status,
                'creator_id' => $user->id,
            ]);
            $activityData['grade_ids_data'] = $gradeIds;
            //添加数据
            $activityData['creator_id'] = $user->id;
            $activityData['data_version_name'] = $term->title;
            $activityData['form_instance_id'] = $formInstance->id;
            $result = ActivityInfo::query()->create($activityData);
            if(!empty($activityData['proof_material'])) {
                $filesArr = json_decode(!empty($activityData['proof_material']) ? $activityData['proof_material'] : '[]', true);
                $filesArr = array_column($filesArr ?: [], 'files_id');
                $result->files_id = $filesArr;
            }
            //添加待办审核
            if($status == 'REVIEW' && $doTask == 1) {
                $taskInfo = $this->systemTaskRepository->getTaskInfo($request['activity_category'], $request);

                $beginDate = isset($request['begin_date']) ? $request['begin_date'] : $term->end_date;
                $endDate = isset($request['end_date']) ? $request['end_date'] : $beginDate;

                Tasks::create([
                    'name' => '【' . $term->title . '】' . $taskInfo['name'],
                    'data_version_id' => $term->id,
                    'form_id' => $result->id,
                    'form_key' => $request['activity_category'],
                    'start_date' => date('Y-m-d H:i:s'),
                    'end_date' => $endDate,
                    'creator_id' => $user->id,
                    'creator_name' => $user->nickname,
                    'param' => '?id=' . $result->id,
                    'url' => $taskInfo['url'],
                    'menu_id' => $taskInfo['menu_id']
                ]);
            }

            //课题研究新增申报阶段
            if(isset($request['stage']) && !empty($request['stage'])) {
                $proofMaterial = json_decode($result->proof_material, true);

                if($request['stage'] == 1) {
                    StudyStage::create([
                        'activity_id' => $result->id,
                        'stage' => $request['stage'],
                        'begin_date' => $request['begin_date'],
                        'end_date' => $request['end_date'],
                        'resources' => $result->proof_material,
                        'status' => $oldStatus == 2 ? 0 : 1
                    ]);
                } else {
                    $sbbFiles = collect($proofMaterial)->where('field', 'sbb')->first();
                    $lxzmFiles = collect($proofMaterial)->where('field', 'lxzm')->first();

                    StudyStage::create([
                        'activity_id' => $result->id,
                        'stage' => 1,
                        'begin_date' => $request['begin_date'],
                        'end_date' => $request['end_date'],
                        'resources' => $sbbFiles ? json_encode([$sbbFiles]) : '',
                        'status' => 2
                    ]);

                    $stageLxData = [
                        'activity_id' => $result->id,
                        'stage' => $request['stage'],
                        'resources' => $lxzmFiles ? json_encode([$lxzmFiles]) : '',
                        'status' => $lxzmFiles ? 1 : 0
                    ];

                    if($request['lx_begin_date']) {
                        $stageLxData['begin_date'] = $request['lx_begin_date'];
                    }
                    if($request['lx_end_date']) {
                        $stageLxData['end_date'] = $request['lx_end_date'];
                    }
                    StudyStage::create($stageLxData);
                }
            }

            $partNames  = [];
            //添加主持人
            if(!empty($request['compere'])) {
                if (in_array($request['activity_category'], $this->partNamesArr)){
                    $partNames['host_name'] = $request['compere'];
                }else{
                    $this->participantRepository->addParticipant($result->id, explode(',', $request['compere']), 'COMPERE');
                }
            }

            //添加参加教师
            if(!empty($request['participant'])) {
                if (in_array($request['activity_category'], $this->partNamesArr)){
                    $partNames['part_name'] = $request['participant'];
                }else{
                    $this->participantRepository->addParticipant($result->id, explode(',', $request['participant']), 'PARTICIPANT');
                }
            }
            if (!empty($partNames)){
                $partNames['activity_info_id'] = $result->id;
                ActivityInfoPartNames::query()->create($partNames);
            }

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    /**
     * @Description: 活动单条数据
     * @Author: kzj
     * @datetime: 2023-02-28
     */
    public function one($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }
        $result = ActivityInfo::where('id', $request['id'])->with('creator', 'participants', 'instance:id,status,comment', 'stages', 'partNames')->first();
        if($result->proof_material){
            $proof = json_decode($result->proof_material,1);
            foreach ($proof as $key => &$value) {
                $files = Files::where('id', $value['files_id'])->select('is_push')->first();
                if($files) {
                    $value['is_push'] = $files->is_push;
                }else{
                    $value['is_push'] = 0;
                }
            }
            $result->proof_material = json_encode($proof,1);
        }
        // dd($result);
        return $result;
    }

    /**
     * @Description: 活动编辑
     * @Author: qiankun
     * @datetime: 2025-06-24
     */
    public function edit($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }
        /**
        if($request['activity_category'] == 'TEACHING_REFLECT_TABLE') {//教学反思（案例）一学期只能加一个数据
            $activityResponse = ActivityInfo::leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
                ->where('activity_info.data_version_id',$request['data_version_id'])
                ->where('activity_info.id','!=',$request['id'])
                ->where('status','!=','FILL_IN')
                ->where('activity_info.activity_category',$request['activity_category'])
                ->where('activity_info.deleted',0)
                ->first();
            if($activityResponse) {
                throw new \Exception('一学期只能添加一个');
            }
        }**/
        $status = 'REVIEW';
        $oldStatus = !empty($request['status']) ? $request['status'] : '';
        if(isset($request['status']))
            $status = $request['status'] == 1 ? 'REVIEW' : 'FILL_IN';
        $user = Auth::user();
        $term = Term::where('id', $request['data_version_id'])->first();
        $doTask = isset($request['do_task']) ? $request['do_task'] : 0;
        unset($request['file']);

        // 复用数据提交不用审核
        if(isset($request['copy_id']) && $request['copy_id'] > 0) {
            $status = 'PASS';
        }


        try{
            DB::beginTransaction();
            $gradeIds = $request['grade'] ?? '';
            //请求数据处理
            $activityData = $this->activityRepository->dealRequestData($request);
            $activityData['data_version_name'] = $term->title;
            $filesArr = !empty($activityData['proof_material']) ? json_decode($activityData['proof_material'], true) : '';
            $filesArr   =   array_column($filesArr?:[], 'files_id');
            //编辑数据
            $activityData['updater_id'] = $user->id;
            $activityData['grade_ids_data'] = $gradeIds;
            $result = ActivityInfo::whereId($request['id'])->update($activityData);
            $activityInfo = ActivityInfo::whereId($request['id'])->with('participants', 'compere')->first();
            $activityInfo->files_id = $filesArr;
            //编辑状态及审核信息
            FormInstance::whereId($activityInfo->form_instance_id)->update([
                'data_version_id' => $request['data_version_id'],
                'data_version_name' => $term->title,
                'status' => $status,
                'updater_id' => $user->id
            ]);

            //处理有驳回的数据
            Tasks::where('form_id', $request['id'])->where('form_key', $activityInfo->activity_category)->where('status', 1)->where('type', 3)->update(['status' => 2]);
            // 待办处理
            $task = Tasks::where('form_id', $request['id'])->where('form_key', $activityInfo->activity_category)->where('status', 1)->first();
            if(!$task && $doTask == 1) {
                $taskInfo = $this->systemTaskRepository->getTaskInfo($request['activity_category'], $request);

                $beginDate = isset($request['begin_date']) ? $request['begin_date'] : $term->end_date;
                $endDate = isset($request['end_date']) ? $request['end_date'] : $beginDate;

                Tasks::create([
                    'name' => '【' . $term->title . '】' . $taskInfo['name'],
                    'data_version_id' => $term->id,
                    'form_id' => $activityInfo->id,
                    'form_key' => $request['activity_category'],
                    'start_date' => date('Y-m-d H:i:s'),
                    'end_date' => $endDate,
                    'creator_id' => $user->id,
                    'creator_name' => $user->nickname,
                    'param' => '?id=' . $activityInfo->id,
                    'url' => $taskInfo['url'],
                    'menu_id' => $taskInfo['menu_id']
                ]);
            }

            //课题研究编辑申报阶段
            if(isset($request['stage']) && !empty($request['stage'])) {

                StudyStage::where('activity_id', $activityInfo->id)
                    ->where('stage', $request['stage'])
                    ->update([
                        'begin_date' => $request['begin_date'],
                        'end_date' => $request['end_date'],
                        'resources' => $activityInfo->proof_material,
                        'status' => $oldStatus == 2 ? 0 : 1
                    ]);
            }
            //课题研究新增申报阶段
            if(isset($request['stage']) && in_array($request['stage'], [1, 2])) {
                if($request['stage'] == 1) {
                    StudyStage::where('activity_id', $activityInfo->id)
                    ->where('stage', $request['stage'])
                    ->update([
                        'begin_date' => $request['begin_date'],
                        'end_date' => $request['end_date'],
                        'resources' => $activityInfo->proof_material,
                        'status' => $oldStatus == 2 ? 0 : 1
                    ]);
                } else {
                    $proofMaterial = json_decode($activityInfo->proof_material, true);
                    $sbbFiles = collect($proofMaterial)->where('field', 'sbb')->first();
                    $lxzmFiles = collect($proofMaterial)->where('field', 'lxzm')->first();

                    StudyStage::where('activity_id', $activityInfo->id)
                        ->where('stage', 1)
                        ->update([
                            'begin_date' => $request['begin_date'],
                            'end_date' => $request['end_date'],
                            'resources' => $sbbFiles ? json_encode([$sbbFiles]) : '',
                            'status' => 2
                        ]);

                    StudyStage::updateOrCreate([
                        'activity_id' => $activityInfo->id,
                        'stage' => $request['stage']
                    ], [
                        'begin_date' => $request['lx_begin_date'],
                        'end_date' => $request['lx_end_date'],
                        'resources' => $lxzmFiles ? json_encode([$lxzmFiles]) : '',
                        'status' => $lxzmFiles ? 1 : 0
                    ]);
                }
            }

            $partNames  = [];
            //编辑主持人
            if(!empty($request['compere'])) {
                if (in_array($activityInfo->activity_category, $this->partNamesArr)){
                    $partNames['host_name'] = $request['compere'];
                }else {
                    $comperes = explode(',', $request['compere']);
                    $pus = $activityInfo->participants_users;
                    if (empty($pus->pere)) {
                        $this->participantRepository->addParticipant($request['id'], $comperes, 'COMPERE');
                    } else {
                        $isSame = array_diff_assoc($comperes, $pus->pere, 'COMPERE');
                        if (!empty($isSame)) {
                            $this->participantRepository->addParticipant($request['id'], $comperes, 'COMPERE');
                        }
                    }
                }
            }
            //编辑参加教师
            if(!empty($request['participant'])) {
                if (in_array($activityInfo->activity_category, $this->partNamesArr)){
                    $partNames['part_name'] = $request['participant'];
                }else {
                    $participants = explode(',', $request['participant']);
                    $pus = $activityInfo->participants_users;
                    if (empty($pus->pant)) {
                        $this->participantRepository->addParticipant($request['id'], $participants);
                    } else {
                        $isSame = array_diff_assoc($participants, $activityInfo->pant);
                        if (!empty($isSame)) {
                            $this->participantRepository->addParticipant($request['id'], $participants);
                        }
                    }
                }
            }
            if (!empty($partNames)){
                if ($activityInfo->partNames()->exists()) {
                    $activityInfo->partNames()->update($partNames);
                }else{
                    ActivityInfoPartNames::query()->create([
                        'activity_info_id' => $activityInfo->id,
                        'part_name' => $partNames['part_name'] ?? '',
                        'host_name' => $partNames['host_name'] ?? '',
                    ]);
                }
            }

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    /**
     * @Description: 活动审核
     * @Author: kzj
     * @datetime: 2023-02-28
     */
    public function check($request)
    {
        if(!$request['form_instance_id']) {
            throw new \Exception('参数缺失！');
        }
        if(empty($request['status'])) {
            throw new \Exception('必须勾选审核结果！');
        }
        $user = Auth::user();

        try{
            DB::beginTransaction();

            $result = FormInstance::where('id', $request['form_instance_id'])
                ->update([
                    'status' => $request['status'],
                    'comment' => $request['comment'],
                    'updater_id' => $user->id,
                ]);

            //修改待办事项
            Tasks::where('form_id', $request['form_id'])->where('form_key', $request['activity_category'])->update(['status' => 2]);

            //如果是驳回，重新给申报人发起待办事项
            if($request['status'] == 'REVIEW_FAIL'){
                $task = Tasks::where('form_id', $request['form_id'])->where('form_key', $request['activity_category'])->where('type', 1)->orderBy('id', 'desc')->first();

                if($task) {
                    $taskInfo = $this->systemTaskRepository->getTaskInfo($request['activity_category'], $request, 'edit');
                    Tasks::create([
                        'name' => $task->name.'驳回',
                        'type' => 3,
                        'data_version_id' => $task->data_version_id,
                        'form_id' => $task->form_id,
                        'form_key' => $request['activity_category'],
                        'start_date' => date('Y-m-d H:i:s'),
                        'end_date' => date('Y-m-d H:i:s'),
                        'c_user_id' => $task->creator_id,
                        'c_user_name' => $task->creator_name,
                        'creator_id' => $user->id,
                        'creator_name' => $user->nickname,
                        'param' => '?id=' . $request['form_id'],
                        'url' => $taskInfo['url'],
                        'menu_id' => $taskInfo['menu_id']
                    ]);
                }
            }

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    /**
     * @Description: 活动删除
     * @Author: kzj
     * @datetime: 2023-02-28
     */
    public function del($request)
    {
        if(!$request['id']) {
            throw new \Exception('ID参数缺失！');
        }

        $activity = ActivityInfo::whereId($request['id'])->first();

        try{
            DB::beginTransaction();

            $result = ActivityInfo::whereId($request['id'])->update(['deleted' => 1]);

            Tasks::where('form_key', $activity->activity_category)->where('form_id', $activity->id)->where('status', 1)->delete();

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    /**
     * @Description: 申报上传数据
     * @Author: kzj
     * @datetime: 2023-03-14
     */
    public function uploadStage($request)
    {

        if(!$request['stage'] || !$request['activity_id']) {
            throw new \Exception('参数缺失！');
        }
        // dd($request);
        $user = Auth::user();
        unset($request['file']);
        $files = $this->activityRepository->dealUploadFile($request['files']);

        $activity = ActivityInfo::whereId($request['activity_id'])->first();
        if($activity->stage == 2) {
           if($request['stage'] > 2) {
                throw new \Exception('非当前申报阶段，不能填写上传！');
           }
        } else {
            if($activity->stage != $request['stage']) {
                throw new \Exception('非当前申报阶段，不能填写上传！');
            }
        }

        try{
            DB::beginTransaction();
            if(!empty($files)) {
                if($request['stage'] == 1) {
                    ActivityInfo::whereId($request['activity_id'])->update(['proof_material' => json_encode($files)]);
                }

                $request['resources'] = json_encode($files);
            }
            unset($request['files']);

            // 中期阶段提交即通过不需要审核
            $request['status'] = $request['stage'] == 3 ? 2 : 1;

            $result = StudyStage::updateOrCreate([
                'activity_id' => $request['activity_id'],
                'stage' => $request['stage']
            ], $request);

            // 中期阶段提交即通过不需要审核,更新项目阶段
            if($request['stage'] == 3) {
                $stage = ++$request['stage'];
                ActivityInfo::whereId($request['activity_id'])->update(['stage' => $stage]);
            }

            //修改待办事项
            Tasks::where('form_key', $activity->activity_category)->where('form_id', $activity->id)->update(['status' => 2]);

            //添加新待办事项
            $beginDate = isset($request['begin_date']) ? $request['begin_date'] : date('Y-m-d H:i:s');
            $endDate = isset($request['end_date']) ? $request['end_date'] : $beginDate;

            if($request['stage'] == 3) {
                // 中期阶段提交即通过不需要审核
                $taskInfo = $this->systemTaskRepository->getTaskInfo($activity->activity_category, $request, 'stage');
                Tasks::create([
                    'name' => '【' . $activity->data_version_name . '】' . $taskInfo['name'],
                    'data_version_id' => $activity->data_version_id,
                    'form_id' => $activity->id,
                    'form_key' => $activity->activity_category,
                    'start_date' => $activity->begin_date,
                    'end_date' => $activity->end_date,
                    'type' => 2,
                    'c_user_id' => $activity->creator_id,
                    'creator_id' => $user->id,
                    'creator_name' => $user->nickname,
                    'param' => '?id=' . $activity->id,
                    'url' => $taskInfo['url'],
                    'menu_id' => $taskInfo['menu_id']
                ]);
            } else {
                $taskInfo = $this->systemTaskRepository->getTaskInfo($activity->activity_category, $request);
                Tasks::create([
                    'name' => '【' . $activity->data_version_name . '】' . $taskInfo['name'],
                    'data_version_id' => $activity->data_version_id,
                    'form_id' => $activity->id,
                    'form_key' => $activity->activity_category,
                    'start_date' => $beginDate,
                    'end_date' => $endDate,
                    'creator_id' => $user->id,
                    'creator_name' => $user->nickname,
                    'param' => '?id=' . $activity->id,
                    'url' => $taskInfo['url'],
                    'menu_id' => $taskInfo['menu_id']
                ]);
            }

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    /**
     * @Description: 申报审核数据
     * @Author: kzj
     * @datetime: 2023-03-14
     */
    public function checkStage($request)
    {
        if(!$request['stage'] || !$request['activity_id']) {
            throw new \Exception('参数缺失！');
        }
        if(empty($request['status'])) {
            throw new \Exception('必须勾选审核结果！');
        }
        $now = now();
        $user = Auth::user();
        $activity = ActivityInfo::whereId($request['activity_id'])->first();
        $stageData = StudyStage::where('activity_id', $activity->id)->where('stage', $request['stage'])->first();

        if($activity->stage != $request['stage']) {
            throw new \Exception('非当前申报阶段，无法审核！');
        }
        if(!$stageData) {
            throw new \Exception('当前申报阶段还没有上传材料，无法审核！');
        }

        try{
            DB::beginTransaction();

            $request['checker'] = $user->id;
            $request['check_date'] = $now;
            $result = StudyStage::where('activity_id', $request['activity_id'])
                ->where('stage', $request['stage'])
                ->update($request);

            //更新申报阶段
            if($request['status'] == 2 && $request['stage'] < 4) {
                $stage = ++$request['stage'];
                ActivityInfo::whereId($request['activity_id'])->update(['stage' => $stage]);
            }

            //修改待办事项
            Tasks::where('form_key', $activity->activity_category)->where('form_id', $activity->id)->where('type', 1)->update(['status' => 2]);
            //添加新待办事项
            $taskInfo = $this->systemTaskRepository->getTaskInfo($activity->activity_category, $request, 'stage');

            //如果是驳回，重新给申报人发起待办事项
            if($request['status'] == 3){
                $task = Tasks::where('form_key', $activity->activity_category)->where('form_id', $activity->id)->first()->toArray();

                Tasks::create([
                    'name' => $task['name'].'驳回',
                    'type' => 3,
                    'data_version_id' => $activity->data_version_id,
                    'form_id' => $activity->id,
                    'form_key' => $activity->activity_category,
                    'start_date' => $activity->begin_date,
                    'end_date' => $activity->end_date,
                    'c_user_id' => $activity->creator_id,
                    'c_user_name' => $task['creator_name'],
                    'creator_id' => $user->id,
                    'creator_name' => $user->nickname,
                    'param' => '?id=' . $activity->id,
                    'url' => $taskInfo['url'],
                    'menu_id' => $taskInfo['menu_id']
                ]);
            } else {
                Tasks::create([
                    'name' => '【' . $activity->data_version_name . '】' . $taskInfo['name'],
                    'data_version_id' => $activity->data_version_id,
                    'form_id' => $activity->id,
                    'form_key' => $activity->activity_category,
                    'start_date' => $activity->begin_date,
                    'end_date' => $activity->end_date,
                    'type' => 2,
                    'c_user_id' => $activity->creator_id,
                    'creator_id' => $user->id,
                    'creator_name' => $user->nickname,
                    'param' => '?id=' . $activity->id,
                    'url' => $taskInfo['url'],
                    'menu_id' => $taskInfo['menu_id']
                ]);
            }

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    /**
     * @Description: 获取活动操作日志信息数据
     * @Author: kzj
     * @datetime: 2023-02-21
     */
    public function getLogInfo($category, $type = 'list', $request)
    {
        $optName = "查看";
        switch($type) {
            case "list":
                $optName = '查看';
                break;
            case "add":
                $optName = '添加';
                break;
            case "edit":
                $optName = '编辑';
                break;
            case "del":
                $optName = '删除';
                break;
            case "check":
                $optName = '审核';
                break;
        }

        $name = "类别错误，请核实！";
        $pid = 0;
        switch($category) {
            case "TEARRESEARCH_OPEN_TABLE":
                $pid = 17;
                $name = '教学研究-公开教学';
                break;
            case "TEARRESEARCH_EXCHANGE_TABLE":
                $pid = 18;
                $name = '教学研究-经验交流【教学】';
                break;
            case "EW_EXCHANGE_EXPERIENCE_TABLE":
                $pid = 18;
                $name = '教学研究-经验交流【教育】';
                break;
            case "TEARRESEARCH_SUBJECT_STUDY_TABLE":
                $pid = 19;
                $name = '教学研究-课题研究【教学】';
                break;
            case "EW_SUBJECT_RESEARCH_TABLE":
                $pid = 19;
                $name = '教学研究-课题研究【教育】';
                break;
            case "TEARRESEARCH_PUBLISH_TABLE":
                $pid = $request['pubications_publish_type'] == '128' ? 21 : 20;
                $t = $request['pubications_publish_type'] == '128' ? '论著发表' : '论文发表';
                $name = '教学研究-' . $t . '【教学】';
                break;
            case "EW_PAPER_PUBLISH_TABLE":
                $pid = $request['pubications_publish_type'] == '128' ? 21 : 20;
                $t = $request['pubications_publish_type'] == '128' ? '论著发表' : '论文发表';
                $name = '教学研究-' . $t . '【教育】';
                break;
            case "TEARRESEARCH_DEVELOP_SUBJECT_TABLE":
                $pid = 22;
                $name = '教学研究-开发科目';
                break;
            case "EW_SOCIAL_PRACTICE_TABLE":
                $pid = 26;
                $name = '教育工作-社会实践';
                break;
            case "EW_CLASS_MEETING_TABLE":
                $pid = 27;
                $name = '教育工作-班队会';
                break;
            case "EW_THEME_ACTIVITY_TABLE":
                $pid = 28;
                $name = '教育工作-主题活动';
                break;
            case "TEACHERTRAINING_DEVELOPCOURSE_TABLE":
                $pid = 29;
                $name = '教师培训-开发课程';
                break;
            case "TEACHERTRAINING_OUTTRAINING_TABLE":
                $pid = 32;
                $name = '教师培训-外出培训';
                break;
            case "TEACHERTRAINING_OTHER_TABLE":
                $pid = 33;
                $name = '教师培训-其他培训';
                break;
        }

        $menuId = 0;
        $menuData = Menu::wherePid($pid)->whereName($optName)->first();
        if($menuData) {
            $menuId = $menuData->id;
        }

        $result = [
            'id' => $menuId,
            'title' => $name . $optName,
            'content' => $name . $optName
        ];

        return $result;
    }

    /**
     * @Description: 生成相关文件数据
     * @Author: kzj
     * @datetime: 2023-05-31
     */
    public function generateStage($request)
    {
        if(!$request['activity_id'] || !$request['stage']) {
            throw new \Exception('参数缺失！');
        }
        unset($request['file']);
        unset($request['files']);

        $activity = ActivityInfo::where('id', $request['activity_id'])->with('creator', 'compereUser', 'participantUser')->first();
        // dd($request, $activity->toArray());
        $now = now();
        $savePath = public_path('back-end/uploadfiles/image/' . $now->format('Ym'));
        if(!is_readable($savePath)) {
            mkdir($savePath, 0777, true);
        }

        try{
            DB::beginTransaction();

            if($activity->stage == 2) {
                $fileInfo = $this->generateLxzs($activity, $savePath, $request['begin_date']);
            } else {
                $fileInfo = $this->generateJtzs($activity, $savePath, $request['end_date']);
            }

            $request['resources'] = json_encode($fileInfo);

            $result = StudyStage::updateOrCreate([
                'activity_id' => $request['activity_id'],
                'stage' => $request['stage']
            ], $request);

            DB::commit();
        }catch(\Exception $e){
            DB::rollback();
            throw new \Exception($e->getMessage());
        }

        return $result;
    }

    // 生成立项证书
    public function generateLxzs($activity, $savePath, $date)
    {
        $imagePath = public_path('app/images/lxzs.jpg');
        $img = Image::make($imagePath)->resize(1704, 1240);

        $creatorName = $this->to_unicode($activity->creator->nickname);
        $activityName = $this->to_unicode($activity->name);
        $year = $this->to_unicode(Carbon::parse($date)->format('Y'));
        $markDate = $this->to_unicode($date);

        $img->text($creatorName, 140, 536, function($font) {
            //$fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($activityName, 425, 640, function($font) {
            //$fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($year, 898, 710, function($font) {
            //$fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($markDate, 1230, 1040, function($font) {
            //$fontPath = public_path('app/fonts/st.ttf');
            //$font->file($fontPath);
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });

        $fileKey = md5($activityName.$year.$markDate);
        $fileName = $fileKey.'.png';

        $img->save($savePath . '/' . $fileName);

        $fileSave = $this->generateFileSave($activity->stage, $fileKey, $fileName);

        return $fileSave;
    }

    // 生成结题证书
    public function generateJtzs($activity, $savePath, $date)
    {
        // 主题名称、学校名称、主持人、参与教师、结题时间
        $compere = $activity->compereUser->pluck('nickname')->implode(', ');
        $participant = $activity->participantUser->pluck('nickname')->implode(', ');

        $activityName = $this->to_unicode($activity->name);
        $schoolName = $this->to_unicode('上海市徐汇区东理工大学附属小学');
        $host = $this->to_unicode($compere);
        $join = $this->to_unicode($participant);
        $markDate = $this->to_unicode($date);

        $imagePath = public_path('app/images/jtzs.jpg');
        $img = Image::make($imagePath)->resize(1704, 1240);
        $img->text($activityName, 425, 542, function($font) {
            $font->file('./app/fonts/st.ttf');
            // $font->file(public_path('app\fonts\st.ttf'));
            $font->size(35);
        });
        $img->text($schoolName, 485, 632, function($font) {
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($host, 455, 712, function($font) {
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($join, 425, 795, function($font) {
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });
        $img->text($markDate, 1220, 1040, function($font) {
            $font->file('./app/fonts/st.ttf');
            $font->size(35);
        });

        // $img->save(public_path('app/images/111.png'));
        // dd(1);

        $fileKey = md5($activityName.$host.$join.$markDate);
        $fileName = $fileKey.'.png';

        $img->save($savePath . '/' . $fileName);

        $fileSave = $this->generateFileSave($activity->stage, $fileKey, $fileName);

        return $fileSave;
    }

    public function generateFileSave($stage, $fileKey, $fileName)
    {
        $now = now();
        $fileShowName = $stage == 2 ? '立项证书.png' : '结题证书.png';
        $field = $stage == 2 ? 'lxzm' : 'jtzs';

        $fileObj = File::create([
            'file_name' => $fileShowName,
            'file_key'  => $fileKey,
            'extension' => 'png',
            'file_path' => 'image/'.$now->format('Ym').'/'.$fileName,
            'file_dir'  => '/back-end/uploadfiles/'
        ]);

        $result[] = [
            'id'        => $fileObj->id,
            'editable'  => true,
            'fileName'  => $fileShowName,
            'filePath'  => $fileObj->id.'/'.$fileKey,
            'extension' => 'png',
            'field'     => $field
        ];

        return $result;
    }

    // 将 utf-8 字符串转为 Unicode 编码格式
    function to_unicode($string)
    {
        $str = mb_convert_encoding($string, 'UCS-2', 'UTF-8');
        $arrstr = str_split($str, 2);
        $unistr = '';
        foreach ($arrstr as $n) {
            $dec = hexdec(bin2hex($n));
            $unistr .= '&#' . $dec . ';';
        }
        return $unistr;
    }

    /**
     * 删除
     * @author qiankun
     * @datetime 2025-03-18
     */
    public function push($request)
    {
        $id = $request['id'];
        $activityInfo = ActivityInfo::query()->where(['id' => $id])->firstOrFail();
        $activityInfo->is_push  = $activityInfo->is_push ? 0 : 1;
        $activityInfo->save();
        return $activityInfo->is_push;
    }

    /**
     * 推送
     * @author qiankun
     * @datetime 2025-03-18
     */
    public function pushOne($request)
    {
        $id = $request['id'];
        $fileId = $request['file_id'];
        //$activity->save();
        Files::where(['ilk_type' => 1,'ilk_id' => $id,'id' => $fileId])->update(['is_push' => $request['is_push']]);
        return $request['is_push'];
    }
}
?>
